var app = getApp()
import {
  getOrderDetail,
  getPayParam,
  refund,
  removeOrder,
  receiving
} from '../../api/order'
import {
  formatTime
} from '../../utils/util'
Page({
  data: {
    order: null,
    orderDetail: [],
    yunPrice: "0.00",
    hideShopPopup: true,
    standardList: [],
    changeIdx: 0,
    standardPrice: 0,
    newStandard: null,
    sn: '',
    orderStatus: '',
    status: {
      'UNPAID': '等待买家付款',
      'PAID': '等待卖家发货',
      'UNDELIVERED': '等待卖家发货',
      'DELIVERED': '卖家已发货',
      'COMPLETED': '已完成'
    },
    expireTime: '',
    statusImg: {
      'UNPAID': '../../images/newImg/icon/UNPAID.png',
      'PAID': '../../images/newImg/icon/UNPAID.png',
      'UNDELIVERED': '../../images/newImg/icon/UNPAID.png',
      'DELIVERED': '../../images/newImg/icon/DELIVERED.png',
      'COMPLETED': '../../images/newImg/icon/COMPLETED.png'
    },
    reason: '不想要了',
    refundBox: false,
    refundOrder: null,
    refundOptions: [{
        value: '不想要了',
        name: '不想要了',
        checked: 'true'
      },
      {
        value: '地址信息填写错误',
        name: '地址信息填写错误'
      },
      {
        value: '商品错选/多选 (规格、数量等)',
        name: '商品错选/多选 (规格、数量等)'
      },
      {
        value: '商品降价',
        name: '商品降价'
      },
      {
        value: '没用/少用/错用优惠',
        name: '没用/少用/错用优惠'
      },
      {
        value: '发货时间过长',
        name: '发货时间过长'
      },
      {
        value: '商品无货',
        name: '商品无货'
      },
      {
        value: '其他',
        name: '其他'
      },
    ],
    refundInput: false
  },
  closePopupTap() {
    this.setData({
      hideShopPopup: true
    })
  },
  goLogistics(e) {
    let that = this
    wx.navigateTo({
      url: '/pages/logistics/logistics?id=' + that.data.order.sn,
    })
  },
  radioChange(e) {
    console.log('radio发生change事件，携带value值为：', e.detail.value)
    if (e.detail.value == '其他') {
      this.setData({
        reason: '',
        refundInput: true,
      })
    } else {
      this.setData({
        refundInput: false,
        reason: e.detail.value
      })
    }
  },
  subRefund() {
    let that = this
    if (that.data.reason == '') {
      wx.showToast({
        title: '请输入退款原因',
        icon: 'none'
      })
      return
    }
    wx.showModal({
      title: '提醒',
      content: '确认要提交申请吗？',
      confirmColor: '#008B8B',
      async success(res) {
        wx.showLoading({
          title: '加载中...',
          mask: true
        })
        if (res.confirm) {
          console.log(that.data.refundOrder)
          if (that.data.refundTitle == '申请退款') {
            let res = await refund(that.data.refundOrder.sn, that.data.reason, wx.getStorageSync('access_token'))
            that.setData({
              refundBox: false
            })
            if (res && res.code == 10000) {
              wx.hideLoading()

              wx.showToast({
                title: '操作成功',
                icon: 'success',
                duration: 1500,
                success: () => {
                  setTimeout(function () {
                    wx.navigateBack({
                      delta: 1 //返回上一级页面
                    })
                  }, 1500)
                }
              })
            } else {
              wx.showToast({
                title: res.msg,
                icon: 'none'
              })
            }
          } else {
            wx.showLoading({
              title: '加载中...',
              mask: true
            })
            let res = await removeOrder(that.data.refundOrder.sn, that.data.reason, wx.getStorageSync('access_token'))
            wx.hideLoading()
            that.setData({
              refundBox: false
            })
            if (res && res.code == 10000) {
              wx.showToast({
                title: '操作成功',
                icon: 'success',
                duration: 1500,
                success: () => {
                  setTimeout(function () {
                    wx.navigateBack({
                      delta: 1 //返回上一级页面
                    })
                  }, 1500)
                }
              })
            }
          }
        } else {
          wx.hideLoading({
            success: (res) => {},
          })
        }
      }
    })
  },
  async toPayTap(e) {
    wx.showLoading({
      title: '加载中...',
      mask: true
    });
    var that = this;
    var orderId = that.data.order.sn;
    let res = await getPayParam(orderId, wx.getStorageSync('access_token'))
    console.log(res)
    wx.hideLoading()
    that.wxPay(res.data)
  },
  wxPay(params) {
    let that = this
    console.log(params)
    wx.requestPayment({
      timeStamp: params.timeStamp,
      nonceStr: params.nonceStr,
      package: params.package,
      signType: params.signType,
      paySign: params.paySign,
      success: function (res) {
        wx.hideLoading()
        setTimeout(function () {
          wx.showToast({
            title: '支付成功',
          })
          wx.navigateBack({
            delta: 1 //返回上一级页面
          })
        }, 1500)
      },
      fail: function (res) {
        wx.hideLoading();
        wx.showToast({
          title: '已取消支付',
          icon: 'none'
        })
      },
      complete: function (res) {
        wx.hideLoading();
        console.log(res);
      }
    })
  },
  refund(e) {
    // let refundOrder = e.currentTarget.dataset.item
    // let status = e.currentTarget.dataset.status
    // this.setData({
    //   refundBox: true,
    //   refundOrder,
    //   refundTitle: status == 1 ? '申请退款' : '取消订单'
    // })
    wx.showToast({
      title: '请返回列表操作',
      icon: 'none',
      duration: 1500,
      success: () => {
        setTimeout(function () {
          wx.navigateBack({
            delta: 1 //返回上一级页面
          })
        }, 1500)
      }
    })
  },
  toConfirmTap: function (e) {
    let that = this
    let orderId = that.data.order.sn
    wx.showModal({
      title: '确认您已收到商品？',
      content: '',
      async success(res) {
        if (res.confirm) {
          wx.showLoading({
            title: '加载中...',
            mask: true
          })
          let res = await receiving(orderId, wx.getStorageSync('access_token'))
          console.log(res)
          wx.hideLoading()
          if (res && res.code == 10000) {
            wx.showToast({
              title: '操作成功',
              icon: 'success',
              duration: 1500,
              success: () => {
                setTimeout(function () {
                  wx.navigateBack({
                    delta: 1 //返回上一级页面
                  })
                }, 1500)
              }
            })
          } else {
            wx.showToast({
              title: '网络错误',
              icon: 'none'
            })
          }
        }
      }
    })
  },
  dealerPay() {
    let that = this
    let standardList = that.data.standardList
    let stand = that.data.orderDetail.goods[0]
    var standardPrice = that.data.standardPrice
    standardList.forEach(item => {
      item.active = false
    })
    for (var i = 0; i < standardList.length; i++) {
      if (standardList[i].Id == stand.StandardId) {
        standardList[i].active = true
        standardPrice = standardList[i].Price * standardList[i].MinBuy
      }
    }
    that.setData({
      hideShopPopup: false,
      standardPrice
    })
    this.setData({
      standardList,
    })
    wx.hideLoading({
      success: (res) => {},
    })
    // this.labelItemTap()
  },
  labelItemTap(e) {
    var that = this
    let standardList = that.data.standardList
    console.log(e)
    let i = e.currentTarget.dataset.propertyindex
    let detail = that.data.orderDetail.goods[0]
    standardList.forEach(item => {
      item.active = false
    })
    console.log(detail)
    detail.StandardName = standardList[i].Name
    detail.Num = standardList[i].MinBuy
    detail.Price = standardList[i].Price
    that.data.order.Total = standardList[i].Price * standardList[i].MinBuy
    standardList[i].active = true
    that.data.newStandard = standardList[i]
    that.data.newStandard.Num = that.data.newStandard.MinBuy
    that.setData({
      standardPrice: standardList[i].Price * standardList[i].MinBuy,
      standardList,
      order: that.data.order,
      newStandard: that.data.newStandard,
      orderDetail: that.data.orderDetail
    })
    let postData = {
      OrderId: that.data.order.OrderId,
      StandardId: detail.StandardId,
      NewStandard: JSON.stringify(that.data.newStandard),
    }
    app.postForm('order/update_order_detail_standard_by_orderid', postData, res => {
      console.log(res)
      if (res.code == 0) {
        detail.StandardId = that.data.newStandard.Id
        this.setData({
          hideShopPopup: true
        })
      }
    })
  },
  buyNow() {
    wx.showLoading({
      title: '加载中',
    })
    let that = this
    var orderId = that.data.order.OrderId
    let payData = {
      OrderIds: orderId,
      OpenId: app.globalData.openid,
      Type: 'JSAPI'
    }
    app.postForm('order/pay_order_by_orderids', payData, rep => {
      // console.log(rep)
      wx.hideLoading();
      that.wxPay(rep)
    })
  },
  wxPay(params) {
    let that = this
    console.log(params)
    let orderList = that.data.orderList
    wx.requestPayment({
      timeStamp: params.timeStamp,
      nonceStr: params.nonceStr,
      package: params.package,
      signType: 'MD5',
      paySign: params.paySign,
      success: function (res) {
        wx.hideLoading();
        wx.showToast({
          title: '支付成功',
          icon: 'success',
          success: () => {
            setTimeout(function () {
              wx.navigateBack({
                delta: 1 //返回上一级页面
              })
            }, 1500)
          }
        })
      },
      fail: function (res) {
        wx.hideLoading();
        wx.showToast({
          title: '已取消支付',
          icon: 'none'
        })
        that.setData({
          hideShopPopup: true
        })
      },
      complete: function (res) {
        wx.hideLoading();
        console.log(res);
      }
    })
  },
  back() {
    wx.navigateBack({
      delta: 1,
      complete: res => {
        console.log(res)
      }
    })
  },
  onLoad: function (e) {
    var that = this;
    var orderId = e.id
    this.setData({
      statusBarHeight: app.globalData.statusBarHeight,
      titleBarHeight: app.globalData.titleBarHeight
    })
    wx.hideShareMenu()
    console.log(orderId);
    if (!e.share) {
      that.setData({
        share: true
      });
    }
    if (app.globalData.iphone == true) {
      that.setData({
        iphone: 'iphone'
      })
    }
    that.data.orderId = orderId;
    that.setData({
      orderId: orderId
    });
  },
  timeFilter(date) {
    return formatTime(date)
  },
  isToday(str) {
    var time = Date.parse(str.replace(/-/g, '/'))
    time = time + 7200000
    let d = new Date(str).setHours(0, 0, 0, 0)
    let today = new Date().setHours(0, 0, 0, 0)
    let obj = {
      '-86400000': '昨天',
      0: '今天',
      86400000: '明天',
    }
    return obj[d - today]
  },
  async onShow() {
    var that = this
    wx.showLoading()
    let res = await getOrderDetail(that.data.orderId, wx.getStorageSync('access_token'))
    wx.hideLoading()
    let orderStatus = res.data.order.orderStatus
    let expire = res.data.order.createTime
    let expireTime = that.timeFilter(expire)
    let toDay = that.isToday(expire)
    res.data.order.consigneeAddressPath = res.data.order.consigneeAddressPath.split(",").join("")
    if (res && res.code == 10000) {
      that.setData({
        order: res.data.order,
        orderDetail: res.data.orderItems,
        orderStatus,
        expireTime: expireTime.substr(11, 19),
        toDay,
      })
    }
    // app.get('goods/get_dealer_goods_info', res => {
    //   console.log(res)
    //   res.standard.forEach( item => {
    //     item.active = false
    //   })
    //   that.setData({
    //     standardList: res.standard
    //   })
    // })
    // app.get(`order/get_order_by_orderid?OrderId=${this.data.orderId}`,res=>{
    //   wx.hideLoading();
    //   console.log(res)
    //   if(res&&res.code=="0"){
    //     let obj = {
    //       Name: res.Detail[0].StandardName
    //     }
    //     that.setData({
    //       order:res.result,
    //       orderDetail:{goods:res.Detail},
    //       newStandard: obj
    //     })
    //   }else{
    //     wx.showModal({
    //       title: '错误',
    //       content: res.msg,
    //       showCancel: false,
    //       success (res) {
    //         if (res.confirm) {
    //           console.log('用户点击确定')
    //           wx.navigateBack()
    //         }
    //       }          
    //     })
    //   }

    // })
    // // setTimeout(function () {
    // //   wx.request({
    // //     url: app.globalData.urls + '/order/detail',
    // //     data: {
    // //       token: app.globalData.token,
    // //       id: that.data.orderId
    // //     },
    // //     success: (res) => {
    // //       wx.hideLoading();
    // //       if (res.data.code != 0) {
    // //         wx.showModal({
    // //           title: '错误',
    // //           content: res.data.msg,
    // //           showCancel: false
    // //         })
    // //         return;
    // //       }
    // //       that.setData({
    // //         orderDetail: res.data.data
    // //       });
    // //     }
    // //   })
    //   // wx.hideLoading();
    //   // var yunPrice = parseFloat(that.data.yunPrice);
    //   // var allprice = 0;
    //   // var goodsList = that.data.goodsList;
    //   // for (var i = 0; i < goodsList.length; i++) {
    //   //   allprice += parseFloat(goodsList[0].price) * goodsList[0].number;
    //   // }
    //   // that.setData({
    //   //   allGoodsPrice: allprice,
    //   //   yunPrice: yunPrice
    //   // });
    // // }, 800)
  },
  wuliuDetailsTap: function (e) {
    var orderId = e.currentTarget.dataset.id;
    var numberId = e.currentTarget.dataset.number;
    wx.navigateTo({
      url: "/pages/logistics/logistics?id=" + orderId + '&number=' + numberId
    })
  },
  copySn() {
    let that = this
    wx.setClipboardData({
      data: that.data.order.sn,
      success: function (res) {
        wx.showToast({
          title: '复制成功',
          icon: "success"
        });
      }
    })
  },
  confirmBtnTap: function (e) {
    let that = this;
    let orderId = this.data.orderId;
    let formId = e.detail.formId;
    wx.showModal({
      title: '确认您已收到商品？',
      content: '',
      success: function (res) {
        if (res.confirm) {
          wx.showLoading();
          wx.request({
            url: app.globalData.urls + '/order/delivery',
            data: {
              token: app.globalData.token,
              orderId: orderId
            },
            success: (res) => {
              if (res.data.code == 0) {
                that.onShow();
                // 模板消息，提醒用户进行评价
                let postJsonString = {};
                postJsonString.keyword1 = {
                  value: that.data.orderDetail.orderInfo.orderNumber,
                  color: '#173177'
                }
                let keywords2 = '您已确认收货，期待您的再次光临！';
                if (app.globalData.order_reputation_score) {
                  keywords2 += '立即好评，系统赠送您' + app.globalData.order_reputation_score + '积分奖励。';
                }
                postJsonString.keyword2 = {
                  value: keywords2,
                  color: '#173177'
                }
                app.sendTempleMsgImmediately(app.siteInfo.assessorderkey, formId,
                  '/pages/order-detail/order-detail?id=' + orderId, JSON.stringify(postJsonString));
              }
            }
          })
        }
      }
    })
  },
  submitReputation: function (e) {
    let that = this;
    let formId = e.detail.formId;
    let postJsonString = {};
    // postJsonString.token = app.globalData.token;
    // postJsonString.orderId = this.data.orderId;
    let reputations = [];
    // console.log(e);
    let i = 0;
    var commentList = [];
    console.log(this.data.orderDetail);
    for (let index = 0; index < this.data.orderDetail.goods.length; index++) {
      const element = this.data.orderDetail.goods[index];
      element.Content = e.detail.value["goodReputationRemark" + i];
      if (!element.Content) {
        wx.showModal({
          showCancel: false,
          content: "请填写评价内容"
        })
        return;
      }
      let item = {
        "GoodsId": element.GoodsId,
        "CustId": app.globalData.uid,
        "StandardId": element.StandardId,
        "GoodsName": element.StandardName,
        "StandardName": element.StandardName,
        "Thumb": element.Thumb,
        "Images": "[]",
        "Content": element.Content,
        "OrderId": this.data.order.OrderId
      }
      commentList.push(item);
    }


    console.log(commentList);
    app.postForm("/order/insert_order_comment", {
      Json: JSON.stringify(commentList[0])
    }, res => {
      console.log(res);
      if (res && res.code == "0") {
        wx.showModal({
          content: "提交成功",
          success() {
            wx.navigateBack();
          }
        })
      } else {
        wx.showToast({
          title: res.msg,
        })
      }
    })
    // while (e.detail.value["orderGoodsId" + i]) {
    //   let orderGoodsId = e.detail.value["orderGoodsId" + i];
    //   let goodReputation = e.detail.value["goodReputation" + i];
    //   let goodReputationRemark = e.detail.value["goodReputationRemark" + i];

    //   let reputations_json = {};
    //   reputations_json.id = orderGoodsId;
    //   reputations_json.reputation = goodReputation;
    //   reputations_json.remark = goodReputationRemark;

    //   reputations.push(reputations_json);
    //   i++;
    // }
    // postJsonString.reputations = reputations;
    // wx.showLoading();
    // wx.request({
    //   url: app.globalData.urls + '/order/reputation',
    //   data: {
    //     postJsonString: postJsonString
    //   },
    //   success: (res) => {
    //     wx.hideLoading();
    //     if (res.data.code == 0) {
    //       that.onShow();
    //       // 模板消息，通知用户已评价
    //       let postJsonString = {};
    //       postJsonString.keyword1 = { value: that.data.orderDetail.orderInfo.orderNumber, color: '#173177' }
    //       let keywords2 = '感谢您的评价，期待您的再次光临！';
    //       if (app.globalData.order_reputation_score) {
    //         keywords2 += app.globalData.order_reputation_score + '积分奖励已发放至您的账户。';
    //       }
    //       postJsonString.keyword2 = { value: keywords2, color: '#173177' }
    //       app.sendTempleMsgImmediately(app.siteInfo.successorderkey , formId,
    //         '/pages/order-detail/order-detail?id=' + that.data.orderId, JSON.stringify(postJsonString));
    //     }
    //   }
    // })
  }
})